package com.evaluation.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.evaluation.common.Result;
import com.evaluation.entity.Dept;
import com.evaluation.entity.DeptEvaluatingRelation;
import com.evaluation.entity.Teacher;
import com.evaluation.entity.TeacherEvaluatingRelation;
import com.evaluation.entity.CommunityCollege;
import com.evaluation.service.DeptEvaluatingRelationService;
import com.evaluation.service.DeptService;
import com.evaluation.service.TeacherEvaluatingRelationService;
import com.evaluation.service.TeacherService;
import com.evaluation.service.CommunityCollegeService;
import com.evaluation.util.ExcelUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 测评关系管理控制器
 */
@RestController
@RequestMapping("/api/admin/relation")
public class AdminRelationController {

    @Autowired
    private DeptEvaluatingRelationService deptRelationService;

    @Autowired
    private TeacherEvaluatingRelationService teacherRelationService;

    @Autowired
    private DeptService deptService;

    @Autowired
    private TeacherService teacherService;

    @Autowired
    private com.evaluation.service.TeacherPositionService teacherPositionService;

    @Autowired
    private CommunityCollegeService communityCollegeService;

    /**
     * 生成部门测评关系
     */
    @PostMapping("/generate/dept")
    public Result<String> generateDeptRelations() {
        try {
            // 清空现有关系
            deptRelationService.remove(new QueryWrapper<>());

            int totalCount = 0;

            // 1. 生成校领导对部门的测评关系
            totalCount += generateLeaderToDeptRelations();

            // 2. 生成二级学院对职能部门的测评关系
            totalCount += generateCollegeToDeptRelations();

            // 3. 生成职能部门对职能部门的测评关系
            totalCount += generateFunctionToDeptRelations();

            return Result.success("生成部门测评关系成功，共生成 " + totalCount + " 条关系");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("生成部门测评关系失败：" + e.getMessage());
        }
    }

    /**
     * 生成教师测评关系
     */
    @PostMapping("/generate/teacher")
    public Result<String> generateTeacherRelations() {
        try {
            // 清空现有关系
            teacherRelationService.remove(new QueryWrapper<>());

            int totalCount = 0;

            // 根据是否参评（SFCP=0）读取所有被测评教师
            List<Teacher> allTeachers = teacherService.list(
                    new QueryWrapper<Teacher>()
                            .eq("SFCP", "0")
                            .eq("JSZT", "0")
            );

            // 遍历每个被测评教师，根据其部门和岗位生成相应的测评关系
            for (Teacher teacher : allTeachers) {
                String bmbh = teacher.getBmbh();
                String gw = teacher.getGw();

                // 8.2.1 对校领导测评
                if ("11100".equals(bmbh)) {
                    totalCount += generateRelationsForLeader(teacher);
                }
                // 8.2.2 对中层测评（部门主任或二级学院院长）
                else if ("4".equals(gw) || "6".equals(gw)) {
                    totalCount += generateRelationsForMiddleManager(teacher);
                }
                // 8.2.11 对社区教师（行政人员）测评
                else if ("20".equals(gw) && Arrays.asList("11122", "11123", "11124", "11125").contains(bmbh)) {
                    totalCount += generateRelationsForCommunityTeacher(teacher);
                }
                // 8.2.3-8.2.10 对其他行政人员测评
                else if ("20".equals(gw) || "5".equals(gw)) { // 行政人员
                    totalCount += generateRelationsForAdminStaff(teacher);
                }
                // 8.2.11 对社区主任测评
                else if ("11".equals(gw) && Arrays.asList("11122", "11123", "11124", "11125").contains(bmbh)) {
                    totalCount += generateRelationsForCommunityDirector(teacher);
                }
                // 8.2.12 对二级学院专任教师测评
                else if ("21".equals(gw) && Arrays.asList("11200", "11202", "11203", "11205", "11206", "11207").contains(bmbh)) {
                    totalCount += generateRelationsForCollegeTeacher(teacher);
                }
            }

            return Result.success("生成教师测评关系成功，共生成 " + totalCount + " 条关系");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("生成教师测评关系失败：" + e.getMessage());
        }
    }

    /**
     * 查询部门测评关系
     */
    @GetMapping("/dept/list")
    public Result<Page<DeptEvaluatingRelation>> getDeptRelationsList(@RequestParam(defaultValue = "1") Integer page,
                                       @RequestParam(defaultValue = "10") Integer size,
                                       @RequestParam(required = false) String bcpbm,
                                       @RequestParam(required = false) String cpjs,
                                       @RequestParam(required = false) String cpbs) {
        try {
            QueryWrapper<DeptEvaluatingRelation> queryWrapper = new QueryWrapper<>();

            if (bcpbm != null && !bcpbm.trim().isEmpty()) {
                queryWrapper.like("BCPBM", bcpbm);
            }

            if (cpjs != null && !cpjs.trim().isEmpty()) {
                queryWrapper.like("CPJS", cpjs);
            }

            if (cpbs != null && !cpbs.trim().isEmpty()) {
                queryWrapper.eq("CPBS", cpbs);
            }

            queryWrapper.orderByDesc("BH");

            Page<DeptEvaluatingRelation> pageResult = deptRelationService.page(new Page<>(page, size), queryWrapper);

            return Result.success(pageResult);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询部门测评关系失败");
        }
    }

    /**
     * 查询教师测评关系
     */
    @GetMapping("/teacher/list")
    public Result<Page<TeacherEvaluatingRelation>> getTeacherRelationsList(@RequestParam(defaultValue = "1") Integer page,
                                          @RequestParam(defaultValue = "10") Integer size,
                                          @RequestParam(required = false) String bcpjs,
                                          @RequestParam(required = false) String cpjs,
                                          @RequestParam(required = false) String cpbs) {
        try {
            QueryWrapper<TeacherEvaluatingRelation> queryWrapper = new QueryWrapper<>();

            if (bcpjs != null && !bcpjs.trim().isEmpty()) {
                queryWrapper.like("BCPJS", bcpjs);
            }

            if (cpjs != null && !cpjs.trim().isEmpty()) {
                queryWrapper.like("CPJS", cpjs);
            }

            if (cpbs != null && !cpbs.trim().isEmpty()) {
                queryWrapper.eq("CPBS", cpbs);
            }

            queryWrapper.orderByDesc("BH");

            Page<TeacherEvaluatingRelation> pageResult = teacherRelationService.page(new Page<>(page, size), queryWrapper);

            return Result.success(pageResult);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询教师测评关系失败");
        }
    }

    /**
     * 删除部门测评关系
     */
    @DeleteMapping("/dept/{bh}")
    public Result<String> deleteDeptRelation(@PathVariable Integer bh) {
        try {
            boolean result = deptRelationService.removeById(bh);
            if (result) {
                return Result.success("删除成功");
            } else {
                return Result.error("删除失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("删除部门测评关系失败");
        }
    }

    /**
     * 获取部门测评关系详情
     */
    @GetMapping("/dept/{bh}")
    public Result<DeptEvaluatingRelation> getDeptRelationDetail(@PathVariable Integer bh) {
        try {
            DeptEvaluatingRelation relation = deptRelationService.getById(bh);
            if (relation != null) {
                return Result.success(relation);
            } else {
                return Result.error("测评关系不存在");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取部门测评关系详情失败");
        }
    }

    /**
     * 更新部门测评关系
     */
    @PutMapping("/dept/{bh}")
    public Result<String> updateDeptRelation(@PathVariable Integer bh, @RequestBody DeptEvaluatingRelation relation) {
        try {
            relation.setBh(bh);
            boolean result = deptRelationService.updateById(relation);
            if (result) {
                return Result.success("更新成功");
            } else {
                return Result.error("更新失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("更新部门测评关系失败");
        }
    }

    /**
     * 获取教师测评关系详情
     */
    @GetMapping("/teacher/{bh}")
    public Result<TeacherEvaluatingRelation> getTeacherRelationDetail(@PathVariable Integer bh) {
        try {
            TeacherEvaluatingRelation relation = teacherRelationService.getById(bh);
            if (relation != null) {
                return Result.success(relation);
            } else {
                return Result.error("测评关系不存在");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取教师测评关系详情失败");
        }
    }

    /**
     * 更新教师测评关系
     */
    @PutMapping("/teacher/{bh}")
    public Result<String> updateTeacherRelation(@PathVariable Integer bh, @RequestBody TeacherEvaluatingRelation relation) {
        try {
            relation.setBh(bh);
            boolean result = teacherRelationService.updateById(relation);
            if (result) {
                return Result.success("更新成功");
            } else {
                return Result.error("更新失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("更新教师测评关系失败");
        }
    }

    /**
     * 删除教师测评关系
     */
    @DeleteMapping("/teacher/{bh}")
    public Result<String> deleteTeacherRelation(@PathVariable Integer bh) {
        try {
            boolean result = teacherRelationService.removeById(bh);
            if (result) {
                return Result.success("删除成功");
            } else {
                return Result.error("删除失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("删除教师测评关系失败");
        }
    }

    // ========== 私有方法：生成具体的测评关系 ==========

    /**
     * 8.1.1 生成校领导对部门的测评关系
     * 校领导对职能部门的工作实绩和创新工作进行测评
     */
    private int generateLeaderToDeptRelations() {
        int count = 0;

        // 根据BMBH=11100（校长室）读取校领导数据
        List<Teacher> leaders = teacherService.list(
                new QueryWrapper<Teacher>()
                        .eq("BMBH", "11100")
                        .eq("JSZT", "0")
                        .eq("SFCP", "0")
        );

        // 读取职能部门（BMLX=0）
        List<Dept> functionDepts = deptService.list(
                new QueryWrapper<Dept>()
                        .eq("BMLX", "0")
                        .eq("BMZT", "0")
        );

        // 校领导对每个职能部门插入2条记录（工作实绩和创新工作）
        for (Teacher leader : leaders) {
            for (Dept dept : functionDepts) {
                // 1. 工作实绩（CPZBBH=21, CPQZBH=4, CPPX=7）
                DeptEvaluatingRelation relation1 = new DeptEvaluatingRelation();
                relation1.setBcpbmbh(dept.getBmbh());
                relation1.setBcpbm(dept.getBmmc());
                relation1.setCpjsbh(String.valueOf(leader.getJsbh()));
                relation1.setCpjs(leader.getJsxm());
                relation1.setCpjsbmbh("11100");
                relation1.setCpjsbm("校长室");
                relation1.setCpzbbh("21");
                relation1.setCpqzbh("4");
                relation1.setCppx("7");
                relation1.setCpbs("0");
                deptRelationService.save(relation1);
                count++;

                // 2. 创新工作（CPZBBH=24, CPQZBH=7, CPPX=10）
                DeptEvaluatingRelation relation2 = new DeptEvaluatingRelation();
                relation2.setBcpbmbh(dept.getBmbh());
                relation2.setBcpbm(dept.getBmmc());
                relation2.setCpjsbh(String.valueOf(leader.getJsbh()));
                relation2.setCpjs(leader.getJsxm());
                relation2.setCpjsbmbh("11100");
                relation2.setCpjsbm("校长室");
                relation2.setCpzbbh("24");
                relation2.setCpqzbh("7");
                relation2.setCppx("10");
                relation2.setCpbs("0");
                deptRelationService.save(relation2);
                count++;
            }
        }

        return count;
    }

    /**
     * 8.1.2 生成二级学院对职能部门的测评关系
     * 二级学院管理团队对职能部门的服务质量进行测评
     */
    private int generateCollegeToDeptRelations() {
        int count = 0;

        // 读取职能部门（BMLX=0）
        List<Dept> functionDepts = deptService.list(
                new QueryWrapper<Dept>()
                        .eq("BMLX", "0")
                        .eq("BMZT", "0")
        );

        // 从T_TEACHER_POSITION读取GWBH=19或22的教师（教师代表或二级学院行政管理）
        List<com.evaluation.entity.TeacherPosition> positions = teacherPositionService.list(
                new QueryWrapper<com.evaluation.entity.TeacherPosition>()
                        .in("GWBH", Arrays.asList("19", "22"))
        );

        // 每个教师对每个职能部门进行测评
        for (com.evaluation.entity.TeacherPosition position : positions) {
            for (Dept dept : functionDepts) {
                // 服务质量（CPZBBH=22, CPQZBH=5, CPPX=8）
                DeptEvaluatingRelation relation = new DeptEvaluatingRelation();
                relation.setBcpbmbh(dept.getBmbh());
                relation.setBcpbm(dept.getBmmc());
                relation.setCpjsbh(position.getJsbh());
                relation.setCpjs(position.getJsxm());
                relation.setCpjsbmbh(position.getBmbh());
                relation.setCpjsbm(position.getBmmc());
                relation.setCpzbbh("22");
                relation.setCpqzbh("5");
                relation.setCppx("8");
                relation.setCpbs("0");
                deptRelationService.save(relation);
                count++;
            }
        }

        return count;
    }

    /**
     * 8.1.3 生成职能部门对职能部门的测评关系
     * 职能部门管理团队对职能部门的融合协作进行测评
     */
    private int generateFunctionToDeptRelations() {
        int count = 0;

        // 读取职能部门（BMLX=0）
        List<Dept> functionDepts = deptService.list(
                new QueryWrapper<Dept>()
                        .eq("BMLX", "0")
                        .eq("BMZT", "0")
        );

        // 从T_TEACHER_POSITION读取GWBH=18或23的教师（行政代表或职能部门管理）
        List<com.evaluation.entity.TeacherPosition> positions = teacherPositionService.list(
                new QueryWrapper<com.evaluation.entity.TeacherPosition>()
                        .in("GWBH", Arrays.asList("18", "23"))
        );

        // 每个教师对每个职能部门进行测评
        for (com.evaluation.entity.TeacherPosition position : positions) {
            for (Dept dept : functionDepts) {
                // 融合协作（CPZBBH=23, CPQZBH=6, CPPX=9）
                DeptEvaluatingRelation relation = new DeptEvaluatingRelation();
                relation.setBcpbmbh(dept.getBmbh());
                relation.setBcpbm(dept.getBmmc());
                relation.setCpjsbh(position.getJsbh());
                relation.setCpjs(position.getJsxm());
                relation.setCpjsbmbh(position.getBmbh());
                relation.setCpjsbm(position.getBmmc());
                relation.setCpzbbh("23");
                relation.setCpqzbh("6");
                relation.setCppx("9");
                relation.setCpbs("0");
                deptRelationService.save(relation);
                count++;
            }
        }

        return count;
    }

    // ========== 教师测评关系生成方法 ==========

    /**
     * 8.2.1 生成对校领导的测评关系
     * 包括领导评议、服务对象评议、同事互评
     */
    private int generateRelationsForLeader(Teacher leader) {
        int count = 0;

        // 8.2.1.1 领导评议（所有校领导）- 测评指标为校领导（CPZBBH=11），测评权重（CPQZBH=1），排序（CPPX=1）
        List<Teacher> otherLeaders = teacherService.list(
                new QueryWrapper<Teacher>()
                        .eq("BMBH", "11100")
                        .ne("JSBH", leader.getJsbh())
                        .eq("SFCP", "0")
                        .eq("JSZT", "0")
        );
        for (Teacher evaluator : otherLeaders) {
            count += saveTeacherRelation(leader, evaluator, "11", "1", "1");
        }

        // 8.2.1.2 服务对象评议（所有中层）- 测评指标为校领导（CPZBBH=11），测评权重（CPQZBH=2），排序（CPPX=1）
        List<Teacher> middleManagers = teacherService.list(
                new QueryWrapper<Teacher>()
                        .in("GW", Arrays.asList("4", "6"))
                        .eq("SFCP", "0")
                        .eq("JSZT", "0")
        );
        for (Teacher evaluator : middleManagers) {
            count += saveTeacherRelation(leader, evaluator, "11", "2", "1");
        }

        // 8.2.1.3 同事互评（全体教师）- 测评指标为校领导（CPZBBH=11），测评权重（CPQZBH=3），排序（CPPX=1）
        List<Teacher> allTeachers = teacherService.list(
                new QueryWrapper<Teacher>()
                        .notIn("GW", Arrays.asList("1", "2", "3", "4", "6"))
                        .eq("SFCP", "0")
                        .eq("JSZT", "0")
        );
        for (Teacher evaluator : allTeachers) {
            count += saveTeacherRelation(leader, evaluator, "11", "3", "1");
        }

        return count;
    }

    /**
     * 8.2.2 生成对中层的测评关系
     * 部门主任（GW=4）或二级学院院长（GW=6）
     */
    private int generateRelationsForMiddleManager(Teacher middleManager) {
        int count = 0;
        String cpzbbh = "4".equals(middleManager.getGw()) ? "13" : "12"; // 职能中层:13, 专业中层:12
        String cppx = "4".equals(middleManager.getGw()) ? "3" : "2";

        // 8.2.2.1 领导评议（所有校领导）- 测评权重（CPQZBH=1）
        List<Teacher> leaders = teacherService.list(
                new QueryWrapper<Teacher>()
                        .eq("BMBH", "11100")
                        .eq("SFCP", "0")
                        .eq("JSZT", "0")
        );
        for (Teacher evaluator : leaders) {
            count += saveTeacherRelation(middleManager, evaluator, cpzbbh, "1", cppx);
        }

        // 8.2.2.2 服务对象评议（本部门员工）- 测评权重（CPQZBH=2）
        List<Teacher> deptStaff = teacherService.list(
                new QueryWrapper<Teacher>()
                        .eq("BMBH", middleManager.getBmbh())
                        .ne("JSBH", middleManager.getJsbh())
                        .eq("SFCP", "0")
                        .eq("JSZT", "0")
        );
        for (Teacher evaluator : deptStaff) {
            count += saveTeacherRelation(middleManager, evaluator, cpzbbh, "2", cppx);
        }

        // 8.2.2.3 同事互评（全体中层）- 测评权重（CPQZBH=3）
        List<Teacher> allMiddleManagers = teacherService.list(
                new QueryWrapper<Teacher>()
                        .in("GW", Arrays.asList("4", "6"))
                        .ne("JSBH", middleManager.getJsbh())
                        .eq("SFCP", "0")
                        .eq("JSZT", "0")
        );
        for (Teacher evaluator : allMiddleManagers) {
            count += saveTeacherRelation(middleManager, evaluator, cpzbbh, "3", cppx);
        }

        return count;
    }

    /**
     * 8.2.3-8.2.9 生成对行政人员的测评关系
     * 根据不同部门采用不同的测评规则
     */
    private int generateRelationsForAdminStaff(Teacher adminStaff) {
        int count = 0;
        String bmbh = adminStaff.getBmbh();

        // 8.2.3 除教学、学工、继教、招生以外的行政人员
        List<String> normalDepts = Arrays.asList("11101", "11102", "11103", "11104", "11108", "11110", "11111", "11113", "11114", "11115", "11116", "11126");
        if (normalDepts.contains(bmbh)) {
            count += generateRelationsForNormalAdminStaff(adminStaff);
        }
        // 8.2.4 继教院（11109）
        else if ("11109".equals(bmbh)) {
            count += generateRelationsForJijiaoStaff(adminStaff);
        }
        // 8.2.5 招生办（11112）
        else if ("11112".equals(bmbh)) {
            count += generateRelationsForZhaoshengStaff(adminStaff);
        }
        // 8.2.6 教学部（11105）
        else if ("11105".equals(bmbh)) {
            count += generateRelationsForJiaoxueStaff(adminStaff);
        }
        // 8.2.7 教务行政秘书（二级学院行政人员）
        else if (Arrays.asList("11200", "11202", "11203", "11205", "11206", "11207").contains(bmbh)) {
            count += generateRelationsForCollegeAdminSecretary(adminStaff);
        }
        // 8.2.8 学工部（11106）
        else if ("11106".equals(bmbh)) {
            count += generateRelationsForXuegongStaff(adminStaff);
        }
        // 8.2.9 职业发展中心（11107）
        else if ("11107".equals(bmbh)) {
            count += generateRelationsForZhiyefazhanStaff(adminStaff);
        }

        return count;
    }

    /**
     * 8.2.11 生成对社区教师（行政人员）的测评关系
     */
    private int generateRelationsForCommunityTeacher(Teacher communityTeacher) {
        int count = 0;
        String bcpbmbh = communityTeacher.getBmbh(); // 被测评教师部门编号

        // 8.2.11.1 领导评议（学工副主任+职业发展副主任+社区主任）
        // 8.2.11.1.1 学工主任和职业发展中心主任
        List<Teacher> leaders = teacherService.list(
                new QueryWrapper<Teacher>()
                        .in("BMBH", Arrays.asList("11106", "11107"))
                        .eq("GW", "5") // 部门副主任
                        .eq("SFCP", "0")
                        .eq("JSZT", "0")
        );
        for (Teacher evaluator : leaders) {
            count += saveTeacherRelation(communityTeacher, evaluator, "16", "1", "6");
        }

        // 8.2.11.1.2 社区主任
        List<Teacher> communityDirectors = teacherService.list(
                new QueryWrapper<Teacher>()
                        .eq("BMBH", bcpbmbh)
                        .eq("GW", "11") // 社区主任
                        .eq("SFCP", "0")
                        .eq("JSZT", "0")
        );
        for (Teacher evaluator : communityDirectors) {
            count += saveTeacherRelation(communityTeacher, evaluator, "16", "1", "6");
        }

        // 8.2.11.2 服务对象评议（本社区班主任）
        List<com.evaluation.entity.TeacherPosition> classTeachers = teacherPositionService.list(
                new QueryWrapper<com.evaluation.entity.TeacherPosition>()
                        .eq("GWBH", "24") // 班主任
                        .eq("BMBH", bcpbmbh)
        );
        for (com.evaluation.entity.TeacherPosition position : classTeachers) {
            Teacher evaluator = teacherService.getById(position.getJsbh());
            if (evaluator != null && "0".equals(evaluator.getSfcp()) && "0".equals(evaluator.getJszt())) {
                // 检查是否重复数据
                if (!isRelationExists(communityTeacher, evaluator)) {
                    count += saveTeacherRelation(communityTeacher, evaluator, "16", "2", "6");
                }
            }
        }

        // 8.2.11.3 同事互评（本社区学工）
        List<Teacher> colleagues = teacherService.list(
                new QueryWrapper<Teacher>()
                        .eq("BMBH", bcpbmbh)
                        .eq("GW", "20") // 行政人员
                        .ne("JSBH", communityTeacher.getJsbh()) // 不等于被测评教师编号
                        .eq("SFCP", "0")
                        .eq("JSZT", "0")
        );
        for (Teacher evaluator : colleagues) {
            count += saveTeacherRelation(communityTeacher, evaluator, "16", "3", "6");
        }

        return count;
    }

    /**
     * 8.2.10 生成对社区主任的测评关系
     */
    private int generateRelationsForCommunityDirector(Teacher director) {
        int count = 0;

        // 8.2.10.1 领导评议（学工主任+职业发展主任+学院院长）- 测评指标（CPZBBH=16），测评权重（CPQZBH=1），排序（CPPX=6）
        // 学工主任和职业发展中心主任
        List<Teacher> leaders1 = teacherService.list(
                new QueryWrapper<Teacher>()
                        .in("BMBH", Arrays.asList("11106", "11107"))
                        .eq("GW", "4")
                        .eq("SFCP", "0")
                        .eq("JSZT", "0")
        );
        for (Teacher evaluator : leaders1) {
            count += saveTeacherRelation(director, evaluator, "16", "1", "6");
        }

        // 8.2.10.1.2 取值社区对应学院院长
        // 通过被测评教师部门编号（bcpbmbh）等于社区编号（SQBH）读取社区学院对应表：T_COMMUNITY_COLLEGE中的部门编号(bmbh)
        List<String> collegeBmbhs = communityCollegeService.list(
                new QueryWrapper<CommunityCollege>()
                        .eq("SQBH", director.getBmbh()) // 社区编号等于被测评教师部门编号
        ).stream().map(CommunityCollege::getBmbh).collect(Collectors.toList());

        if (!collegeBmbhs.isEmpty()) {
            // 再通过取出的部门编号(bmbh)等于部门编号（BMBH），岗位为学院院长（GW=6）和是否参评为参评（SFCP=0）等条件读取教师表T_TEACHER中的教师数据
            List<Teacher> collegeDirectors = teacherService.list(
                    new QueryWrapper<Teacher>()
                            .in("BMBH", collegeBmbhs)
                            .eq("GW", "6") // 岗位为学院院长
                            .eq("SFCP", "0") // 是否参评为参评
                            .eq("JSZT", "0")
            );
            for (Teacher evaluator : collegeDirectors) {
                // 测评数据插入测评关系表T_TEACHER_EVALUATING_RELATION，测评指标编号为行政人员（CPZBBH=16），测评权重编号（CPQZBH=1），排序（CPPX=6）
                count += saveTeacherRelation(director, evaluator, "16", "1", "6");
            }
        }

        // 8.2.10.2 服务对象评议（本社区全体+社区班主任）- 测评权重（CPQZBH=2）
        // 本社区全体人员
        List<Teacher> communityStaff = teacherService.list(
                new QueryWrapper<Teacher>()
                        .eq("BMBH", director.getBmbh())
                        .eq("GW", "20")
                        .eq("SFCP", "0")
                        .eq("JSZT", "0")
        );
        for (Teacher evaluator : communityStaff) {
            count += saveTeacherRelation(director, evaluator, "16", "2", "6");
        }

        // 社区班主任
        List<com.evaluation.entity.TeacherPosition> banzhurens = teacherPositionService.list(
                new QueryWrapper<com.evaluation.entity.TeacherPosition>()
                        .eq("GWBH", "24")
                        .eq("BMBH", director.getBmbh())
        );
        for (com.evaluation.entity.TeacherPosition position : banzhurens) {
            Teacher evaluator = teacherService.getById(position.getJsbh());
            if (evaluator != null && "0".equals(evaluator.getSfcp()) && "0".equals(evaluator.getJszt())) {
                count += saveTeacherRelation(director, evaluator, "16", "2", "6");
            }
        }

        // 8.2.10.3 同事互评（社区主任）- 测评权重（CPQZBH=3）
        List<Teacher> otherDirectors = teacherService.list(
                new QueryWrapper<Teacher>()
                        .in("BMBH", Arrays.asList("11122", "11123", "11124", "11125"))
                        .eq("GW", "11")
                        .ne("JSBH", director.getJsbh())
                        .eq("SFCP", "0")
                        .eq("JSZT", "0")
        );
        for (Teacher evaluator : otherDirectors) {
            count += saveTeacherRelation(director, evaluator, "16", "3", "6");
        }

        return count;
    }

    /**
     * 8.2.12 生成对二级学院专任教师的测评关系
     */
    private int generateRelationsForCollegeTeacher(Teacher teacher) {
        int count = 0;

        // 8.2.12.1 领导评议（院长+副院长+培训主管）- 测评指标（CPZBBH=14），测评权重（CPQZBH=1），排序（CPPX=4）
        // 院长+副院长
        List<Teacher> collegeLeaders = teacherService.list(
                new QueryWrapper<Teacher>()
                        .eq("BMBH", teacher.getBmbh())
                        .in("GW", Arrays.asList("6", "7"))
                        .eq("SFCP", "0")
                        .eq("JSZT", "0")
        );
        for (Teacher evaluator : collegeLeaders) {
            count += saveTeacherRelation(teacher, evaluator, "14", "1", "4");
        }

        // 培训主管
        List<com.evaluation.entity.TeacherPosition> trainers = teacherPositionService.list(
                new QueryWrapper<com.evaluation.entity.TeacherPosition>()
                        .eq("GWBH", "8")
                        .eq("BMBH", teacher.getBmbh())
        );
        for (com.evaluation.entity.TeacherPosition position : trainers) {
            Teacher evaluator = teacherService.getById(position.getJsbh());
            if (evaluator != null && "0".equals(evaluator.getSfcp()) && "0".equals(evaluator.getJszt())) {
                count += saveTeacherRelation(teacher, evaluator, "14", "1", "4");
            }
        }

        // 8.2.12.2 服务对象评议（吕延鹏-文理学院全体班主任）- 测评权重（CPQZBH=2）
        if ("吕延鹏".equals(teacher.getJsxm())) {
            List<com.evaluation.entity.TeacherPosition> banzhurens = teacherPositionService.list(
                    new QueryWrapper<com.evaluation.entity.TeacherPosition>()
                            .eq("GWBH", "24")
                            .eq("BMBH", "11200")
            );
            for (com.evaluation.entity.TeacherPosition position : banzhurens) {
                Teacher evaluator = teacherService.getById(position.getJsbh());
                if (evaluator != null && "0".equals(evaluator.getSfcp()) && "0".equals(evaluator.getJszt())) {
                    count += saveTeacherRelation(teacher, evaluator, "14", "2", "4");
                }
            }
        }

        // 8.2.12.3 同事互评（学院全体专任教师，排除培训主管）- 测评权重（CPQZBH=3）
        // 查询培训主管的教师编号
        List<String> trainerJsbhs = teacherPositionService.list(
                new QueryWrapper<com.evaluation.entity.TeacherPosition>()
                        .eq("GWBH", "8")
        ).stream().map(com.evaluation.entity.TeacherPosition::getJsbh).collect(Collectors.toList());

        QueryWrapper<Teacher> queryWrapper = new QueryWrapper<Teacher>()
                .eq("BMBH", teacher.getBmbh())
                .ne("JSBH", teacher.getJsbh())
                .eq("GW", "21")
                .eq("SFCP", "0")
                .eq("JSZT", "0");

        if (!trainerJsbhs.isEmpty()) {
            queryWrapper.notIn("JSBH", trainerJsbhs);
        }

        List<Teacher> colleagues = teacherService.list(queryWrapper);
        for (Teacher evaluator : colleagues) {
            count += saveTeacherRelation(teacher, evaluator, "14", "3", "4");
        }

        return count;
    }

    // ========== 辅助方法：各种具体场景的测评关系生成 ==========

    /**
     * 8.2.3 除教学、学工、继教、招生以外的行政人员
     */
    private int generateRelationsForNormalAdminStaff(Teacher staff) {
        int count = 0;

        // 8.2.3.1 领导评议（本部门主任）- 测评指标（CPZBBH=15），测评权重（CPQZBH=1），排序（CPPX=5）
        List<Teacher> deptDirectors = teacherService.list(
                new QueryWrapper<Teacher>()
                        .eq("GW", "4")
                        .eq("SFCP", "0")
                        .eq("BMBH", staff.getBmbh())
                        .eq("JSZT", "0")
        );
        for (Teacher evaluator : deptDirectors) {
            count += saveTeacherRelation(staff, evaluator, "15", "1", "5");
        }

        // 8.2.3.2 服务对象评议（所有中层）- 测评权重（CPQZBH=2）
        List<Teacher> middleManagers = teacherService.list(
                new QueryWrapper<Teacher>()
                        .in("GW", Arrays.asList("4", "6"))
                        .ne("BMBH", staff.getBmbh())
                        .eq("SFCP", "0")
                        .eq("JSZT", "0")
        );
        for (Teacher evaluator : middleManagers) {
            count += saveTeacherRelation(staff, evaluator, "15", "2", "5");
        }

        // 8.2.3.3 同事互评（除教学、学工以外的行政人员）- 测评权重（CPQZBH=3）
        List<String> adminDepts = Arrays.asList("11101", "11102", "11103", "11104", "11108", "11109", "11110", "11111", "11112", "11113", "11114", "11115", "11116", "11126");
        List<Teacher> colleagues = teacherService.list(
                new QueryWrapper<Teacher>()
                        .in("BMBH", adminDepts)
                        .in("GW", Arrays.asList("20", "5"))
                        .ne("JSBH", staff.getJsbh())
                        .eq("SFCP", "0")
                        .eq("JSZT", "0")
        );
        for (Teacher evaluator : colleagues) {
            count += saveTeacherRelation(staff, evaluator, "15", "3", "5");
        }

        return count;
    }

    /**
     * 8.2.4 继教院行政人员
     */
    private int generateRelationsForJijiaoStaff(Teacher staff) {
        int count = 0;

        // 8.2.4.1 领导评议（本部门主任）
        List<Teacher> deptDirectors = teacherService.list(
                new QueryWrapper<Teacher>()
                        .eq("SFCP", "0")
                        .eq("GW", "4")
                        .eq("BMBH", staff.getBmbh())
                        .eq("JSZT", "0")
        );
        for (Teacher evaluator : deptDirectors) {
            count += saveTeacherRelation(staff, evaluator, "15", "1", "5");
        }

        // 8.2.4.2 服务对象评议（培训主管）
        List<com.evaluation.entity.TeacherPosition> trainers = teacherPositionService.list(
                new QueryWrapper<com.evaluation.entity.TeacherPosition>()
                        .eq("GWBH", "8")
        );
        for (com.evaluation.entity.TeacherPosition position : trainers) {
            Teacher evaluator = teacherService.getById(position.getJsbh());
            if (evaluator != null && "0".equals(evaluator.getSfcp()) && "0".equals(evaluator.getJszt())) {
                count += saveTeacherRelation(staff, evaluator, "15", "2", "5");
            }
        }

        // 8.2.4.3 同事互评（除教学、学工以外的行政人员）
        List<String> adminDepts = Arrays.asList("11101", "11102", "11103", "11104", "11108", "11109", "11110", "11111", "11112", "11113", "11114", "11115", "11116", "11126");
        List<Teacher> colleagues = teacherService.list(
                new QueryWrapper<Teacher>()
                        .eq("SFCP", "0")
                        .in("GW", Arrays.asList("20", "5"))
                        .ne("JSBH", staff.getJsbh())
                        .in("BMBH", adminDepts)
                        .eq("JSZT", "0")
        );
        for (Teacher evaluator : colleagues) {
            count += saveTeacherRelation(staff, evaluator, "15", "3", "5");
        }

        return count;
    }

    /**
     * 8.2.5 招生办行政人员
     */
    private int generateRelationsForZhaoshengStaff(Teacher staff) {
        int count = 0;

        // 8.2.5.1 领导评议（本部门主任）
        List<Teacher> deptDirectors = teacherService.list(
                new QueryWrapper<Teacher>()
                        .eq("SFCP", "0")
                        .eq("GW", "4")
                        .eq("BMBH", staff.getBmbh())
                        .eq("JSZT", "0")
        );
        for (Teacher evaluator : deptDirectors) {
            count += saveTeacherRelation(staff, evaluator, "15", "1", "5");
        }

        // 8.2.5.2 服务对象评议（招生负责人）
        List<com.evaluation.entity.TeacherPosition> recruiters = teacherPositionService.list(
                new QueryWrapper<com.evaluation.entity.TeacherPosition>()
                        .eq("GWBH", "12")
        );
        for (com.evaluation.entity.TeacherPosition position : recruiters) {
            Teacher evaluator = teacherService.getById(position.getJsbh());
            if (evaluator != null && "0".equals(evaluator.getSfcp()) && "0".equals(evaluator.getJszt())) {
                count += saveTeacherRelation(staff, evaluator, "15", "2", "5");
            }
        }

        // 8.2.5.3 同事互评（除教学、学工以外的行政人员）
        List<String> adminDepts = Arrays.asList("11101", "11102", "11103", "11104", "11108", "11109", "11110", "11111", "11112", "11113", "11114", "11115", "11116", "11126");
        List<Teacher> colleagues = teacherService.list(
                new QueryWrapper<Teacher>()
                        .eq("SFCP", "0")
                        .in("GW", Arrays.asList("20", "5"))
                        .ne("JSBH", staff.getJsbh())
                        .in("BMBH", adminDepts)
                        .eq("JSZT", "0")
        );
        for (Teacher evaluator : colleagues) {
            count += saveTeacherRelation(staff, evaluator, "15", "3", "5");
        }

        return count;
    }

    /**
     * 8.2.6 教学部行政人员
     */
    private int generateRelationsForJiaoxueStaff(Teacher staff) {
        int count = 0;

        // 8.2.6.1 领导评议（本部门主任）
        List<Teacher> deptDirectors = teacherService.list(
                new QueryWrapper<Teacher>()
                        .eq("SFCP", "0")
                        .eq("GW", "4")
                        .eq("BMBH", staff.getBmbh())
                        .eq("JSZT", "0")
        );
        for (Teacher evaluator : deptDirectors) {
            count += saveTeacherRelation(staff, evaluator, "15", "1", "5");
        }

        // 8.2.6.2 服务对象评议（二级学院院长和副院长）
        List<Teacher> collegeLeaders = teacherService.list(
                new QueryWrapper<Teacher>()
                        .eq("SFCP", "0")
                        .in("GW", Arrays.asList("6", "7"))
                        .eq("JSZT", "0")
        );
        for (Teacher evaluator : collegeLeaders) {
            count += saveTeacherRelation(staff, evaluator, "15", "2", "5");
        }

        // 8.2.6.3 同事互评（教学部全体和学院秘书）
        List<String> depts = Arrays.asList("11105", "11200", "11202", "11203", "11205", "11206", "11207");
        List<Teacher> colleagues = teacherService.list(
                new QueryWrapper<Teacher>()
                        .eq("SFCP", "0")
                        .in("GW", Arrays.asList("20", "5"))
                        .ne("JSBH", staff.getJsbh())
                        .in("BMBH", depts)
                        .eq("JSZT", "0")
        );
        for (Teacher evaluator : colleagues) {
            count += saveTeacherRelation(staff, evaluator, "15", "3", "5");
        }

        return count;
    }

    /**
     * 8.2.7 教务行政秘书（二级学院行政人员）
     */
    private int generateRelationsForCollegeAdminSecretary(Teacher staff) {
        int count = 0;

        // 8.2.7.1 领导评议（学院院长和副院长）
        List<Teacher> collegeLeaders = teacherService.list(
                new QueryWrapper<Teacher>()
                        .eq("SFCP", "0")
                        .in("GW", Arrays.asList("6", "7"))
                        .eq("JSZT", "0")
        );
        for (Teacher evaluator : collegeLeaders) {
            count += saveTeacherRelation(staff, evaluator, "15", "1", "5");
        }

        // 8.2.7.2 服务对象评议（学院全体，排除院长和副院长）
        List<Teacher> collegeStaff = teacherService.list(
                new QueryWrapper<Teacher>()
                        .eq("SFCP", "0")
                        .notIn("GW", Arrays.asList("6", "7"))
                        .eq("BMBH", staff.getBmbh())
                        .ne("JSBH", staff.getJsbh())
                        .eq("JSZT", "0")
        );
        for (Teacher evaluator : collegeStaff) {
            count += saveTeacherRelation(staff, evaluator, "15", "2", "5");
        }

        // 8.2.7.3 同事互评（教学部全体和学院秘书）
        List<String> depts = Arrays.asList("11105", "11200", "11202", "11203", "11205", "11206", "11207");
        List<Teacher> colleagues = teacherService.list(
                new QueryWrapper<Teacher>()
                        .eq("SFCP", "0")
                        .ne("JSBH", staff.getJsbh())
                        .in("GW", Arrays.asList("20", "5"))
                        .in("BMBH", depts)
                        .eq("JSZT", "0")
        );
        for (Teacher evaluator : colleagues) {
            count += saveTeacherRelation(staff, evaluator, "15", "3", "5");
        }

        return count;
    }

    /**
     * 8.2.8 学工部行政人员
     */
    private int generateRelationsForXuegongStaff(Teacher staff) {
        int count = 0;

        // 8.2.8.1 领导评议（部门主任）
        List<Teacher> deptDirectors = teacherService.list(
                new QueryWrapper<Teacher>()
                        .eq("SFCP", "0")
                        .eq("GW", "4")
                        .eq("BMBH", staff.getBmbh())
                        .eq("JSZT", "0")
        );
        for (Teacher evaluator : deptDirectors) {
            count += saveTeacherRelation(staff, evaluator, "16", "1", "6");
        }

        // 8.2.8.2 服务对象评议（社区全体）
        List<String> communityDepts = Arrays.asList("11122", "11123", "11124", "11125");
        List<Teacher> communityStaff = teacherService.list(
                new QueryWrapper<Teacher>()
                        .eq("SFCP", "0")
                        .eq("GW", "20")
                        .in("BMBH", communityDepts)
                        .eq("JSZT", "0")
        );
        for (Teacher evaluator : communityStaff) {
            count += saveTeacherRelation(staff, evaluator, "16", "2", "6");
        }

        // 8.2.8.3 同事互评（本部员工、职业发展员工和社区主任）
        // 本部员工和职业发展员工
        List<Teacher> colleagues1 = teacherService.list(
                new QueryWrapper<Teacher>()
                        .eq("SFCP", "0")
                        .in("BMBH", Arrays.asList("11106", "11107"))
                        .in("GW", Arrays.asList("20", "5"))
                        .ne("JSBH", staff.getJsbh())
                        .eq("JSZT", "0")
        );
        for (Teacher evaluator : colleagues1) {
            count += saveTeacherRelation(staff, evaluator, "16", "3", "6");
        }

        // 社区主任
        List<Teacher> communityDirectors = teacherService.list(
                new QueryWrapper<Teacher>()
                        .in("BMBH", communityDepts)
                        .eq("GW", "11")
                        .eq("SFCP", "0")
                        .eq("JSZT", "0")
        );
        for (Teacher evaluator : communityDirectors) {
            count += saveTeacherRelation(staff, evaluator, "16", "3", "6");
        }

        return count;
    }

    /**
     * 8.2.9 职业发展中心行政人员
     */
    private int generateRelationsForZhiyefazhanStaff(Teacher staff) {
        int count = 0;

        // 8.2.9.1 领导评议（部门主任）
        List<Teacher> deptDirectors = teacherService.list(
                new QueryWrapper<Teacher>()
                        .eq("SFCP", "0")
                        .eq("GW", "4")
                        .eq("BMBH", staff.getBmbh())
                        .eq("JSZT", "0")
        );
        for (Teacher evaluator : deptDirectors) {
            count += saveTeacherRelation(staff, evaluator, "16", "1", "6");
        }

        // 8.2.9.2 服务对象评议（社区全体）
        List<String> communityDepts = Arrays.asList("11122", "11123", "11124", "11125");
        List<Teacher> communityStaff = teacherService.list(
                new QueryWrapper<Teacher>()
                        .eq("SFCP", "0")
                        .in("GW", Arrays.asList("20", "5"))
                        .in("BMBH", communityDepts)
                        .eq("JSZT", "0")
        );
        for (Teacher evaluator : communityStaff) {
            count += saveTeacherRelation(staff, evaluator, "16", "2", "6");
        }

        // 8.2.9.3 同事互评（本部员工、职业发展员工和社区主任）
        // 本部员工和职业发展员工
        List<Teacher> colleagues1 = teacherService.list(
                new QueryWrapper<Teacher>()
                        .eq("SFCP", "0")
                        .in("BMBH", Arrays.asList("11106", "11107"))
                        .in("GW", Arrays.asList("20", "5"))
                        .ne("JSBH", staff.getJsbh())
                        .eq("JSZT", "0")
        );
        for (Teacher evaluator : colleagues1) {
            count += saveTeacherRelation(staff, evaluator, "16", "3", "6");
        }

        // 社区主任
        List<Teacher> communityDirectors = teacherService.list(
                new QueryWrapper<Teacher>()
                        .in("BMBH", communityDepts)
                        .eq("GW", "11")
                        .eq("SFCP", "0")
                        .eq("JSZT", "0")
        );
        for (Teacher evaluator : communityDirectors) {
            count += saveTeacherRelation(staff, evaluator, "16", "3", "6");
        }

        return count;
    }

    /**
     * 保存教师测评关系的通用方法
     */
    /**
     * 检查测评关系是否已存在
     */
    private boolean isRelationExists(Teacher evaluated, Teacher evaluator) {
        QueryWrapper<TeacherEvaluatingRelation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("BCPJSBH", String.valueOf(evaluated.getJsbh()));
        queryWrapper.eq("CPJSBH", String.valueOf(evaluator.getJsbh()));
        
        TeacherEvaluatingRelation existingRelation = teacherRelationService.getOne(queryWrapper);
        return existingRelation != null;
    }

    private int saveTeacherRelation(Teacher evaluated, Teacher evaluator, String cpzbbh, String cpqzbh, String cppx) {
        TeacherEvaluatingRelation relation = new TeacherEvaluatingRelation();
        relation.setBcpjsbh(String.valueOf(evaluated.getJsbh()));
        relation.setBcpjs(evaluated.getJsxm());
        relation.setBcpjsbmbh(evaluated.getBmbh());
        relation.setBcpjsbm(evaluated.getBmmc());
        relation.setCpjsbh(String.valueOf(evaluator.getJsbh()));
        relation.setCpjs(evaluator.getJsxm());
        relation.setCpjsbmbh(evaluator.getBmbh());
        relation.setCpjsbm(evaluator.getBmmc());
        relation.setCpzbbh(cpzbbh);
        relation.setCpqzbh(cpqzbh);
        relation.setCppx(cppx);
        relation.setCpbs("0");
        teacherRelationService.save(relation);
        return 1;
    }


    /**
     * 导出部门测评关系
     */
    @GetMapping("/dept/export")
    public void exportDeptRelations(HttpServletResponse response,
                                    @RequestParam(required = false) String bcpbm,
                                    @RequestParam(required = false) String cpjs,
                                    @RequestParam(required = false) String cpbs) {
        try {
            QueryWrapper<DeptEvaluatingRelation> queryWrapper = new QueryWrapper<>();
            
            // 应用搜索条件
            if (bcpbm != null && !bcpbm.trim().isEmpty()) {
                queryWrapper.like("BCPBM", bcpbm);
            }
            if (cpjs != null && !cpjs.trim().isEmpty()) {
                queryWrapper.like("CPJS", cpjs);
            }
            if (cpbs != null && !cpbs.trim().isEmpty()) {
                queryWrapper.eq("CPBS", cpbs);
            }

            queryWrapper.orderByDesc("BH");
            List<DeptEvaluatingRelation> list = deptRelationService.list(queryWrapper);
            List<Map<String, Object>> exportData = new ArrayList<>();

            for (DeptEvaluatingRelation relation : list) {
                Map<String, Object> map = new LinkedHashMap<>();
                // 按照要求的顺序添加字段
                map.put("测评编号", relation.getBh());
                map.put("被测评部门编号", relation.getBcpbmbh());
                map.put("被测评部门", relation.getBcpbm());
                map.put("测评教师编号", relation.getCpjsbh());
                map.put("测评教师", relation.getCpjs());
                map.put("测评教师部门编号", relation.getCpjsbmbh());
                map.put("测评教师部门", relation.getCpjsbm());
                map.put("测评指标编号", relation.getCpzbbh());
                map.put("测评权重编号", relation.getCpqzbh());
                map.put("测评权重名称", getWeightName(relation.getCpqzbh()));
                map.put("排序", relation.getCppx());
                map.put("第一分数", relation.getFirstscore());
                map.put("第二分数", relation.getTwoscore());
                map.put("第三分数", relation.getThreescore());
                map.put("第四分数", relation.getFourscore());
                map.put("总分", relation.getTotalscore());
                map.put("测评标识", "1".equals(relation.getCpbs()) ? "已测评" : "未测评");
                map.put("测评时间", relation.getCpsj());

                exportData.add(map);
            }

            if (!exportData.isEmpty()) {
                String fileName = "部门测评关系_" + System.currentTimeMillis();
                ExcelUtil.exportExcel(response, fileName, exportData);
            } else {
                // 创建空Excel，使用LinkedHashMap保持顺序
                Map<String, Object> emptyMap = new LinkedHashMap<>();
                emptyMap.put("测评编号", "");
                emptyMap.put("被测评部门编号", "");
                emptyMap.put("被测评部门", "");
                emptyMap.put("测评教师编号", "");
                emptyMap.put("测评教师", "");
                emptyMap.put("测评教师部门编号", "");
                emptyMap.put("测评教师部门", "");
                emptyMap.put("测评指标编号", "");
                emptyMap.put("测评权重编号", "");
                emptyMap.put("测评权重名称", "");
                emptyMap.put("排序", "");
                emptyMap.put("第一分数", "");
                emptyMap.put("第二分数", "");
                emptyMap.put("第三分数", "");
                emptyMap.put("第四分数", "");
                emptyMap.put("总分", "");
                emptyMap.put("测评标识", "");
                emptyMap.put("测评时间", "");
                exportData.add(emptyMap);
                String fileName = "部门测评关系_" + System.currentTimeMillis();
                ExcelUtil.exportExcel(response, fileName, exportData);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 导出教师测评关系
     */
    @GetMapping("/teacher/export")
    public void exportTeacherRelations(HttpServletResponse response,
                                       @RequestParam(required = false) String bcpjs,
                                       @RequestParam(required = false) String cpjs,
                                       @RequestParam(required = false) String cpbs) {
        try {
            QueryWrapper<TeacherEvaluatingRelation> queryWrapper = new QueryWrapper<>();
            
            // 应用搜索条件
            if (bcpjs != null && !bcpjs.trim().isEmpty()) {
                queryWrapper.like("BCPJS", bcpjs);
            }
            if (cpjs != null && !cpjs.trim().isEmpty()) {
                queryWrapper.like("CPJS", cpjs);
            }
            if (cpbs != null && !cpbs.trim().isEmpty()) {
                queryWrapper.eq("CPBS", cpbs);
            }

            queryWrapper.orderByDesc("BH");
            List<TeacherEvaluatingRelation> list = teacherRelationService.list(queryWrapper);
            List<Map<String, Object>> exportData = new ArrayList<>();

            for (TeacherEvaluatingRelation relation : list) {
                Map<String, Object> map = new LinkedHashMap<>();
                // 按照要求的顺序添加字段
                map.put("测评编号", relation.getBh());
                map.put("被测评教师编号", relation.getBcpjsbh());
                map.put("被测评教师", relation.getBcpjs());
                map.put("被测评教师部门编号", relation.getBcpjsbmbh());
                map.put("被测评教师部门", relation.getBcpjsbm());
                map.put("测评教师编号", relation.getCpjsbh());
                map.put("测评教师", relation.getCpjs());
                map.put("测评教师部门编号", relation.getCpjsbmbh());
                map.put("测评教师部门", relation.getCpjsbm());
                map.put("测评指标编号", relation.getCpzbbh());
                map.put("测评权重编号", relation.getCpqzbh());
                map.put("测评权重名称", getWeightName(relation.getCpqzbh()));
                map.put("排序", relation.getCppx());
                map.put("第一分数", relation.getFirstscore());
                map.put("第二分数", relation.getTwoscore());
                map.put("第三分数", relation.getThreescore());
                map.put("第四分数", relation.getFourscore());
                map.put("总分", relation.getTotalscore());
                map.put("测评标识", "1".equals(relation.getCpbs()) ? "已测评" : "未测评");
                map.put("测评时间", relation.getCpsj());

                exportData.add(map);
            }

            if (!exportData.isEmpty()) {
                String fileName = "教师测评关系_" + System.currentTimeMillis();
                ExcelUtil.exportExcel(response, fileName, exportData);
            } else {
                // 创建空Excel，使用LinkedHashMap保持顺序
                Map<String, Object> emptyMap = new LinkedHashMap<>();
                emptyMap.put("测评编号", "");
                emptyMap.put("被测评教师编号", "");
                emptyMap.put("被测评教师", "");
                emptyMap.put("被测评教师部门编号", "");
                emptyMap.put("被测评教师部门", "");
                emptyMap.put("测评教师编号", "");
                emptyMap.put("测评教师", "");
                emptyMap.put("测评教师部门编号", "");
                emptyMap.put("测评教师部门", "");
                emptyMap.put("测评指标编号", "");
                emptyMap.put("测评权重编号", "");
                emptyMap.put("测评权重名称", "");
                emptyMap.put("排序", "");
                emptyMap.put("第一分数", "");
                emptyMap.put("第二分数", "");
                emptyMap.put("第三分数", "");
                emptyMap.put("第四分数", "");
                emptyMap.put("总分", "");
                emptyMap.put("测评标识", "");
                emptyMap.put("测评时间", "");
                exportData.add(emptyMap);
                String fileName = "教师测评关系_" + System.currentTimeMillis();
                ExcelUtil.exportExcel(response, fileName, exportData);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据权重编号获取权重名称
     */
    private String getWeightName(String cpqzbh) {
        if (cpqzbh == null || cpqzbh.trim().isEmpty()) {
            return "";
        }
        
        switch (cpqzbh) {
            case "1":
                return "领导评议";
            case "2":
                return "服务对象评议";
            case "3":
                return "同事互评";
            case "4":
                return "工作实践";
            case "5":
                return "服务质量";
            case "6":
                return "融合协作";
            case "7":
                return "创新工作";
            default:
                return cpqzbh;
        }
    }
}
